import pymysql

global environment, connection, cursor


class SQLFunc:

    # 链接数据库信息
    @staticmethod
    def get_cur(environment):
        global connection, cursor
        if environment == "test":
            connection = pymysql.Connect(host='114.55.254.249', user='root', passwd='dxT@DiR5Ti4jIGEi', port=3306, db='erp', charset='utf8')
            cursor = connection.cursor()  # 生成游标对象
        elif environment == "UAT":
            connection = pymysql.Connect(host='47.111.241.192', user='root', passwd='dxT@DiR5Ti4jIGEi', port=3306, db='erp', charset='utf8')
            cursor = connection.cursor()
        elif environment == "stable":
            connection = pymysql.Connect(host='47.74.145.174', user='root', passwd='dxT@DiR5Ti4jIGEi', port=3306, db='erp', charset='utf8')
            cursor = connection.cursor()
        return {"conn": connection, "cur": cursor}

    @staticmethod
    def execute_sql(connection, cursor, sql_str):
        connection.commit()
        try:
            # 执行sql语句
            cursor.execute(sql_str)
            data = cursor.fetchall()
            if len(data) == 0:
                return None
            # 提交到数据库执行
            connection.commit()
            # 关闭数据库连接
            connection.close()
            return data[0]
        except Exception as e:
            print(e.__context__)
            # 如果发生错误则回滚
            connection.rollback()
            # 关闭数据库连接
            connection.close()
